import { login, getInfo, logout } from '@/api/login'
import useAuthStore from '@/stores/modules/auth.ts'

interface UserInfo {
  name: string
  permissionList: string[]
}

interface UserState {
  token: string | undefined
  userInfo: UserInfo | undefined
}

const userStore = defineStore('user', {
  // 存储数据state
  state: (): UserState => {
    return {
      // token
      token: undefined,
      userInfo: undefined,
    }
  },
  // 配置持久化
  persist: {
    storage: localStorage,
    pick: ['token'],
  },
  // 该函数没有上下文数据，所以获取state中的变量需要使用this
  actions: {
    // 获取用户数据
    async getUserInfo() {
      const res = await getInfo()
      this.userInfo = res.data
      // 添加用户权限列表
      const authStore = useAuthStore()
      authStore.setPermissionList(res.data.permissionList)
    },
    async userLogin(username: string, password: string) {
      //走登录逻辑 向后台请求登录接口 获取token 保存到缓存中
      const res = await login(username, password)
      this.token = res.data
    },
    async userLogout() {
      // 走退出登录逻辑 清除缓存中的token
      await logout()
      this.userInfo = undefined
      this.token = undefined
    },
  },
})

// 对外暴露方法
export default userStore
